package com.hc.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.entity.QcEquipment;
import com.hc.entity.QcFilestore;
import com.hc.entity.QcMonitor;
import com.hc.mapper.QcEquipmentMapper;
import com.hc.mapper.QcFilestoreMapper;
import com.hc.mapper.QcMonitorMapper;
import com.hc.model.QcMonitorModel;
import com.hc.model.QcRecordStatusModel;
import com.hc.service.QcFilestoreService;
import com.hc.service.QcMonitorService;
import com.hc.util.ExcelUtils;
import com.hc.util.QcEqMonExcelUtil;
import com.hc.util.UserInfoPost;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiuZhiHao
 * @date 2019/8/28 14:07
 * 描述:
 **/
@Service
public class QcMonitorServiceImpl  extends ServiceImpl<QcMonitorMapper,QcMonitor> implements QcMonitorService {

    @Autowired
    private QcMonitorMapper qcMonitorMapper;
    @Autowired
    private QcFilestoreService qcFilestoreService;
    @Autowired
    private UserInfoPost userInfoPost;
    @Autowired
    private QcFilestoreMapper qcFilestoreMapper;
    @Autowired
    private QcEquipmentMapper qcEquipmentMapper;


    /**
     * 根据设置id和当前时间，将符合要求的巡检记录的是否添加液氮的状态字段值设置为是，设置为1
     * @param eqId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addIsAddLiquidNitrogen(Integer eqId) {
        //如果设备id是对应的胚胎库1,2,3则执行操作，否则不处理
        if (eqId.equals(233)||eqId.equals(234)||eqId.equals(235)){
            Date date = new Date();
            QcMonitor qcMonitor = new QcMonitor();
            qcMonitor.setEqId(eqId);
            qcMonitor.setCreateTime(date);
            qcMonitor.setIsAddLiquidNitrogen("1");
            qcMonitorMapper.insert(qcMonitor);
        }
    }

    /**
     * 新增监测记录
     * @param qcMonitorModel
     */
    @Override
    public void saveQcMonitor(QcMonitorModel qcMonitorModel) {
        qcMonitorModel.setCreateTime(new Date());
        qcMonitorMapper.insert(qcMonitorModel);
        Long id = qcMonitorModel.getId();
        List<String> images = qcMonitorModel.getImages();
        if (CollectionUtils.isNotEmpty(images)) {
            List<QcFilestore> list = new ArrayList<>();
            images.forEach(s -> {
                QcFilestore qcFilestore = new QcFilestore();
                qcFilestore.setCreateBy(qcMonitorModel.getCreateBy());
                qcFilestore.setCreateTime(new Date());
                qcFilestore.setFileUrl(s);
                qcFilestore.setRecordId(id);
                qcFilestore.setRecordType("2");
                list.add(qcFilestore);
            });
            qcFilestoreService.saveBatch(list);
        }

    }

    @Override
    public Date getbeforeMaintainTime(Integer eqId) {
        LambdaQueryWrapper<QcMonitor> last = Wrappers.lambdaQuery(new QcMonitor())
                .eq(QcMonitor::getEqId, eqId)
                .orderByDesc(QcMonitor::getCreateTime)
                .last("LIMIT 1");
        QcMonitor qcMonitor = qcMonitorMapper.selectOne(last);
        if (null == qcMonitor) {
            return null;
        }
        return qcMonitor.getMaintainTime();
    }

    @Override
    public List<QcMonitorModel> findEqDeatil(QcRecordStatusModel qcRecordStatusModel) {
        List<QcMonitorModel> qcMonitorModels = qcEquipmentMapper.findEqDeatilForMon(qcRecordStatusModel);
        if (CollectionUtils.isNotEmpty(qcMonitorModels)) {
            Set<Long> collect1 = qcMonitorModels.stream().map(QcMonitorModel::getId).collect(Collectors.toSet());
            List<QcFilestore> list = qcFilestoreMapper.selectList(Wrappers.lambdaQuery(new QcFilestore()).eq(QcFilestore::getRecordType, "2")
                    .in(QcFilestore::getRecordId, collect1)
                    .orderByAsc(QcFilestore::getCreateTime));
            Map<Long, List<QcFilestore>> collect2 = list.stream().collect(Collectors.groupingBy(QcFilestore::getRecordId));
            qcMonitorModels.forEach(m -> {
                List<QcFilestore> list1 = collect2.get(m.getId());
                if (CollectionUtils.isNotEmpty(list1)) {
                    List<String> collect = list1.stream().filter(h -> StringUtils.isNotEmpty(h.getFileUrl())).map(QcFilestore::getFileUrl).collect(Collectors.toList());
                    m.setImages(collect);
                }
            });
            Set<String> collect = qcMonitorModels.stream().map(QcMonitorModel::getCreateBy).collect(Collectors.toSet());
            Map<String, String> allSysUserinfoByIds = userInfoPost.getAllSysUserinfoByIds(collect);
            qcMonitorModels.forEach(s -> {
                String createBy = s.getCreateBy();
                String createName = allSysUserinfoByIds.get(createBy);
                s.setCreateName(createName);
            });
            return qcMonitorModels;
        }
        return null;
    }


    @Override
    public List<QcEquipment> getMonEq(Integer commonlyUsed,String enable) {
        List<QcEquipment> list =new ArrayList<>();
        if (StringUtils.isBlank(enable)){
            switch (commonlyUsed) {
                case 1:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .eq(QcEquipment::getClassifyId, "6")
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                case 2:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .eq(QcEquipment::getClassifyId, "9")
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                case 3:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .in(QcEquipment::getClassifyId, Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"))
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                case 4:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .eq(QcEquipment::getClassifyId, "3")
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                default:
                    break;
            }
        }else {
            switch (commonlyUsed) {
                case 1:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .eq(QcEquipment::getEnable, enable)
                            .eq(QcEquipment::getClassifyId, "6")
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                case 2:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .eq(QcEquipment::getEnable, enable)
                            .eq(QcEquipment::getClassifyId, "9")
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                case 3:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .eq(QcEquipment::getEnable, enable)
                            .in(QcEquipment::getClassifyId, Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"))
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                case 4:
                    list = qcEquipmentMapper.selectList(Wrappers.lambdaQuery(new QcEquipment())
                            .eq(QcEquipment::getEnable, enable)
                            .eq(QcEquipment::getClassifyId, "3")
                            .select(QcEquipment::getId, QcEquipment::getDeviceName));
                    break;
                default:
                    break;
            }
        }
        return list;
    }

    @Override
    public void exportExcel(HttpServletResponse response, QcRecordStatusModel qcRecordStatusModel) {
        List<QcMonitorModel> eqDeatil = findEqDeatil(qcRecordStatusModel);
        Map<String, List<QcMonitorModel>> collect = eqDeatil.stream().collect(Collectors.groupingBy(QcMonitorModel::getCommonlyUsed));
        Set<String> commonlyUseds = collect.keySet();
        HSSFWorkbook workbook = new HSSFWorkbook();
        commonlyUseds.forEach(s->{
            //各种类型设备excel适配器
            List<QcMonitorModel> qcMonitorModels = collect.get(s);
            QcEqMonExcelUtil.exportExcel(workbook,s,qcMonitorModels);
        });
        try {
            String fileName = "监测记录查询导出";
            ExcelUtils.closeResponse(response,fileName,workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
